package android.funtionality;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonParser {
	String json;

	public JSONObject obtenerJSONdeURL(String url, List<NameValuePair> parametro) {
		DefaultHttpClient cliente = new DefaultHttpClient();
		String finalUrl = url + "?";
		for (NameValuePair objNameValuePair : parametro) {
			finalUrl += objNameValuePair.getName() + "="
					+ objNameValuePair.getValue() + "&";
		}
		finalUrl = finalUrl.substring(0, finalUrl.length() - 1);
		HttpPost post = new HttpPost(finalUrl);
		InputStream input = null;
		try {
			//post.setEntity(new UrlEncodedFormEntity(parametro));
			HttpResponse respuesta = cliente.execute(post);
			HttpEntity entidad = respuesta.getEntity();
			input = entidad.getContent();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			BufferedReader lector = new BufferedReader(new InputStreamReader(
					input, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = lector.readLine()) != null) {
				sb.append(line + "n");
			}
			input.close();
			json = sb.toString();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONObject jobj = null;
		try {
			jobj = new JSONObject(json);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return jobj;
	}
}
